<template>
  <el-dialog
    title="上传固件"
    :visible.sync="open"
    :before-close="cancel"
    width="600px"
    append-to-body
  >
    <el-form ref="form" :model="form" :rules="rules" class="dialog-form">
      <el-form-item label="固件版本" prop="versionNo">
        <el-input v-model="form.versionNo" placeholder="请输入固件版本" />
      </el-form-item>

      <el-form-item
        label="OTA 文件（例如 xiaozhi.bin）"
        prop="otaUrl"
        class="el-form-item-upload-div"
      >
        <el-upload
          :action="uploadBase.uploadFileUrl"
          :before-upload="handleBeforeUpload"
          :limit="uploadBase.limit"
          :on-error="handleUploadError"
          :on-exceed="handleExceed"
          :on-success="handleUploadSuccessOTA"
          :headers="uploadBase.headers"
          class="upload-file-uploader upload-btn"
          ref="fileUploadOTA"
          :show-file-list="false"
        >
          <el-button plain icon="el-icon-upload2" size="mini">选择 OTA 文件</el-button>
        </el-upload>
      </el-form-item>

      <!-- 文件列表 -->
      <transition-group
        class="upload-file-list el-upload-list el-upload-list--text"
        name="el-fade-in-linear"
        tag="ul"
        v-if="form.otaUrl"
      >
        <li class="el-upload-list__item ele-upload-list__item-content" key="otaUrl">
          <span class="el-icon-document"> {{ getLastPartOfUrl(form.otaUrl) }} </span>
          <div class="ele-upload-list__item-content-action">
            <el-link :underline="false" @click="handleDelete('ota')" type="danger"
              >删除</el-link
            >
          </div>
        </li>
      </transition-group>

      <el-form-item
        label="镜像文件（例如 merged-binary.bin）"
        class="el-form-item-upload-div"
        prop="imgUrl"
      >
        <el-upload
          :action="uploadBase.uploadFileUrl"
          :before-upload="handleBeforeUpload"
          :limit="uploadBase.limit"
          :on-error="handleUploadError"
          :on-exceed="handleExceed"
          :on-success="handleUploadSuccesMerged"
          :headers="uploadBase.headers"
          :show-file-list="false"
          class="upload-file-uploader upload-btn"
          ref="fileUploadMerged"
        >
          <el-button plain icon="el-icon-upload2" size="mini">选择镜像文件</el-button>
        </el-upload>
      </el-form-item>

      <!-- 文件列表 -->
      <transition-group
        class="upload-file-list el-upload-list el-upload-list--text"
        name="el-fade-in-linear"
        tag="ul"
        v-if="form.imgUrl"
      >
        <li class="el-upload-list__item ele-upload-list__item-content" key="imgUrl">
          <span class="el-icon-document"> {{ getLastPartOfUrl(form.imgUrl) }} </span>
          <div class="ele-upload-list__item-content-action">
            <el-link :underline="false" @click="handleDelete('img')" type="danger"
              >删除</el-link
            >
          </div>
        </li>
      </transition-group>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";
import { getFirmwareList, addFirmware } from "@/api/login";
export default {
  props: {
    open: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: "",
    },
  },
  data() {
    return {
      form: {},
      rules: {
        versionNo: [{ required: true, trigger: "blur", message: "固件版本不能为空" }],
      },
      uploadBase: {
        number: 0,
        uploadList: [],
        baseUrl: process.env.VUE_APP_BASE_API,
        uploadFileUrl: process.env.VUE_APP_BASE_API + "/api/file/oss/upload", // 上传文件服务器地址
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        fileSize: 5,
        fileType: ["bin"],
        limit: 1,
      },
      loading: false,
    };
  },
  methods: {
    cancel() {
      this.$emit("cancel");
    },
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const { form, id } = this;
            this.form.productId = id;
            this.loading = true;
            await addFirmware(form);
            this.$modal.msgSuccess("添加成功");
            this.cancel();
            this.$emit("getList");
          } catch (error) {
            console.error("添加错误", error);
          } finally {
            this.loading = false;
          }
        }
      });
    },
    resetFormFun() {
      this.form = {
        versionNo: "",
        otaUrl: "",
        otaLen: null,
        imgUrl: "",
        imgLen: null,
        productId: null,
      };
      this.resetForm("form");
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      const { fileType, fileSize } = this.uploadBase;
      if (fileType) {
        const fileName = file.name.split(".");
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (fileSize) {
        const isLt = file.size / 1024 / 1024 < fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...");
      return true;
    },
    // 文件个数超出
    handleExceed() {
      const { limit } = this.uploadBase;
      this.$modal.msgError(`上传文件数量不能超过 ${limit} 个!`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    handleUploadSuccesMerged(res, file) {
      this.handleUploadSuccess(res, file, "fileUploadOTA", "imgUrl", "imgLen");
    },
    // 上传成功回调
    handleUploadSuccessOTA(res, file) {
      this.handleUploadSuccess(res, file, "fileUploadMerged", "otaUrl", "otaLen");
    },
    handleUploadSuccess(res, file, formField, urlField, lenField) {
      const { message, code } = res;
      const { size } = file;
      if (code === 200) {
        this.form[urlField] = message;
        this.form[lenField] = size;
        this.$refs[`${formField}`].clearFiles();
        this.$modal.closeLoading();
        this.$modal.msgSuccess("上传成功");
      }
    },
    // 删除文件
    handleDelete(type) {
      if (type == "ota") {
        this.form.otaUrl = "";
        this.form.otaLen = null;
        this.$refs[`fileUploadOTA`].clearFiles();
      } else {
        this.form.imgUrl = "";
        this.form.imgLen = null;
        this.$refs[`fileUploadMerged`].clearFiles();
      }
    },
    getLastPartOfUrl(url) {
      // 使用split方法将URL按斜杠分割成数组
      const parts = url.split("/");
      // 获取数组中最后一个元素
      return parts[parts.length - 1];
    },
  },
};
</script>

<style scoped lang="scss">
.firmware {
  margin: 0 0 22px 0;
  .firmware-top {
    margin-bottom: 22px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}
.upload-btn {
  display: block;
}
.el-form-item-upload {
  display: block;
  width: 100%;
}
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
  background: #e4e7ed;
  margin-top: -20px;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
  padding: 0 5px;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
</style>

<style>
.el-form-item-upload-div .el-form-item__label {
  float: none !important;
}
</style>
